package com.zl;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/socket")
public class WebSocket {

	private static int onlineCount = 0;
	
	private static Map<String,WebSocket> socketPools = Collections.synchronizedMap(new HashMap<String,WebSocket>());
	
	private Session session;
	
	 @OnOpen
	    public void onOpen(Session session) throws Exception{
	            this.session=session;
	            addOnlineCount();
	            socketPools.put(session.getId(), this);
	            //onMessage("Welcome to DEYAO danmu ^_^" , this.session) ;
	    }
	 
	 @OnClose
	    public void onClose(Session session) throws Exception{
	            this.session=session;
	            subOnlineCount();
	            socketPools.remove(this.session.getId());
	            //onMessage("Welcome to DEYAO danmu ^_^" , this.session) ;
	    }
	 
	 @OnMessage
	 public void onMessage(String message,Session session) throws Exception{
		 mass(message);
	 }
	 public static void mass(String message){
		 for(String key : socketPools.keySet()){
			 
			 try {
				synchronized (socketPools.get(key)) {
					socketPools.get(key).session.getAsyncRemote().sendText(message);
				} 
			} catch (Exception e) {
				System.out.println("fail");
				socketPools.remove(socketPools.get(key).session.getId());
				String msg = socketPools.get(key).session.getId()+"has been disconnected";
				mass(msg);
			}
		 }
	 }
	 @OnError
	    public void onError(Session session, Throwable error) {
	        System.out.println("发生错误");
	        error.printStackTrace();
	    }
	 
	 private static  synchronized void addOnlineCount(){
		 WebSocket.onlineCount++;
	 }
	 
	 private static synchronized void subOnlineCount(){
		 WebSocket.onlineCount--;
	 }
	 
	 private static synchronized int getOnlineCount(){
		 return onlineCount;
	 }
}
